import React, { useEffect } from 'react';
import styles from './index.less';
import planIcon from '@/assets/img/plan_icon.png';
import { Drawer, message, Space, Spin, Timeline } from 'antd';
import { useSetState } from 'ahooks';
import { TRDefault } from '#/components';
import { postFindOperationLog } from '../../service';
import { HttpCode } from '#/utils/contacts';
import moment from 'moment/moment';
import { DownSquareOutlined, UpSquareOutlined } from '#/utils/antdIcons';
import { connect } from 'umi';
import { TjTable } from '@/pages/ETrade/components';
import { smoothOptions } from '../../helper';
import { columns } from './helper';

export const LogModal = ({ visible, onCancel, searchForm, type }) => {
  const [state, setState] = useSetState({
    loading: true,
    error: false,
    data: [],
    currentData: [],
  });

  const _onCancel = () => {
    onCancel?.();
  };

  const fetch = async () => {
    const res = await postFindOperationLog({
      markDate: searchForm?.calendarDate,
      stationId: searchForm?.stationId,
      marketId: searchForm.marketId,
      saveType: searchForm.saveType,
      type, // 和Ai策略里的操作日志共用一个接口，Ai策略那点开传1，外面点开传2
    });
    if (res && res.statusCode === HttpCode.SUCCESS) {
      const _data = (res?.data || []).map((item, index) => ({
        ...item,
        id: index + 1,
        isSpread: false,
      }));
      setState({
        data: _data,
        error: false,
      });
    } else {
      setState({
        error: true,
      });
      message.info(res?.message || '系统异常');
    }
  };

  // 加载日志
  useEffect(() => {
    setState({
      loading: true,
    });
    if (visible) {
      (async () => {
        await fetch();
        setState({
          loading: false,
        });
      })();
    }
  }, [visible]);

  const changeIsSpread = (index, value) => {
    const _data = _.cloneDeep(state.data);
    _data[index].isSpread = value;
    setState({
      data: _data,
    });
  };

  const _render = () => {
    return (
      <div className={styles.lgoList}>
        <Timeline style={{ width: '100%' }}>
          {state.data.map((item, index) => (
            <Timeline.Item key={index}>
              <div className={styles.title}>
                <div className={styles.top}>
                  <Space>
                    <div className={styles.date}>
                      {moment(item.operationTime).format('YYYY.MM.DD HH:mm:ss')}
                    </div>
                    <div className={styles.type}>策略更新</div>
                    <div
                      className={styles.spread}
                      onClick={() => changeIsSpread(index, !item.isSpread)}
                    >
                      {item?.isSpread ? <UpSquareOutlined /> : <DownSquareOutlined />}
                    </div>
                  </Space>
                  <Space>
                    <div className={styles.date}>操作人:</div>
                    <div>{item.operationUser}</div>
                  </Space>
                </div>
                {item.isSpread && (
                  <>
                    <div className={styles.bottom}>
                      平滑算法:
                      {smoothOptions.find((i) => i.value === item.smoothStatus)?.label || ''}
                    </div>
                    <div className={styles.table}>
                      <TjTable dataSource={item.dataList || []} columns={columns} />
                    </div>
                  </>
                )}
              </div>
            </Timeline.Item>
          ))}
        </Timeline>
      </div>
    );
  };

  return (
    <Drawer
      width={680}
      visible={visible}
      onClose={_onCancel}
      title={
        <div className={styles.titleDiv}>
          <img src={planIcon} className={styles.titleLogo} alt={''} />
          <span>操作日志</span>
        </div>
      }
      footer={null}
    >
      <div className={styles.body}>
        {state.loading ? (
          <Spin spinning />
        ) : state.error ? (
          <TRDefault type={'emptysm'} message={'系统异常'} />
        ) : state.data?.length === 0 ? (
          <TRDefault type={'emptysm'} message={'暂无数据'} />
        ) : (
          <div className={styles.content}>{_render()}</div>
        )}
      </div>
    </Drawer>
  );
};

export default connect(({ shortTermForecastingRedesignV2 }) => ({
  searchForm: shortTermForecastingRedesignV2.searchForm,
}))(LogModal);
